package com.itcpeng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcpeng.dao.PackageDao;
import com.itcpeng.entity.PageResult;
import com.itcpeng.pojo.Package;
import com.itcpeng.service.PackageService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = PackageService.class)
public class PackageServiceImpl implements PackageService {

    @Autowired
    private PackageDao packageDao;

    //添加套餐
    @Override
    public void add(Package pkg, Integer[] checkgroupIds) {
        //调用dao插入套餐
        packageDao.add(pkg);
        //获得id
        Integer id = pkg.getId();
        if (checkgroupIds != null) {
            for (Integer checkgroupId : checkgroupIds) {
                //添加套餐和检查组的关系
                packageDao.addPackageGroup(id, checkgroupId);
            }
        }
    }

    //套餐分页
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Package> packages = packageDao.selectBycond(queryString);
        return new PageResult(packages.getTotal(), packages.getResult());
    }

    //删除
    @Override
    public void deleteAll(Integer id) {
        packageDao.delete(id);
        packageDao.deleteAll(id);
    }

    //根据id查询
    @Override
    public Package findById(Integer id) {
        return packageDao.findById(id);
    }

    //根据id查询检查组
    @Override
    public List<Integer> findPakageCheckgroupIds(Integer id) {
        return packageDao.findPakageCheckgroupIds(id);
    }

    //编辑回显
    @Override
    public void edit(Package pkg, Integer[] checkgroupIds) {
        //删除中间表(清理原有的关系)
        packageDao.delete(pkg.getId());
        //向中间边插入数据
        setPackageAndCheckGroupItem(pkg.getId(), checkgroupIds);
        //更新信息
        packageDao.edit(pkg);

    }

    //查询所有套餐
    @Override
    public List<Package> findAll() {
        return packageDao.findAll();
    }

    //根据套餐id执行多表查询(通过编号查询套餐详情)
    @Override
    public Package findByIds(Integer id) {
        return packageDao.findByIds(id);
    }

    //查询套餐
    @Override
    public Package findPackageById(Integer id) {
        return packageDao.findPackageById(id);
    }

    //向中间表插入信息
    public void setPackageAndCheckGroupItem(Integer packageid, Integer[] checkgroupIds) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                map.put("packageid", packageid);
                map.put("checkgroupid", checkgroupId);
                packageDao.setPackageAndCheckGroupItem(map);
            }
        }
    }
}
